package com.dms.modules.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.common.security.SecurityUtils;
import com.dms.common.utils.FileUploadUtils;
import com.dms.modules.community.dto.CommunityPostDTO;
import com.dms.modules.community.dto.CommunityPostDetailDTO;
import com.dms.modules.community.entity.CommunityPost;
import com.dms.modules.community.entity.CommunityLike;
import com.dms.modules.community.entity.CommunityFavorite;
import com.dms.modules.community.entity.CommunityTag;
import com.dms.modules.community.entity.CommunityPostTag;
import com.dms.modules.community.mapper.CommunityPostMapper;
import com.dms.modules.community.mapper.CommunityLikeMapper;
import com.dms.modules.community.mapper.CommunityFavoriteMapper;
import com.dms.modules.community.service.CommunityPostService;
import com.dms.modules.community.service.CommunityTagService;
import com.dms.modules.community.service.CommunityPostTagService;
import com.dms.modules.message.dto.CommunityNotificationDTO;
import com.dms.modules.message.dto.MessageDetailDTO;
import com.dms.modules.message.websocket.MessageWebSocket;
import com.dms.modules.user.service.UserCenterService;
import com.dms.modules.user.vo.UserInfoVO;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommunityPostServiceImpl extends ServiceImpl<CommunityPostMapper, CommunityPost> implements CommunityPostService {

    private final Gson gson = new Gson();

    @Autowired
    private CommunityLikeMapper likeMapper;

    @Autowired
    private CommunityFavoriteMapper favoriteMapper;

    @Autowired
    private MessageWebSocket messageWebSocket;

    @Autowired
    private UserCenterService userCenterService;

    @Autowired
    private CommunityTagService tagService;

    @Autowired
    private CommunityPostTagService postTagService;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPost(CommunityPostDTO postDTO, Long userId) {
        // 验证用户ID
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 验证标签是否存在
        if (CollectionUtils.isNotEmpty(postDTO.getTagIds())) {
            List<CommunityTag> tags = tagService.listByIds(postDTO.getTagIds());
            if (tags.size() != postDTO.getTagIds().size()) {
                throw new BusinessException("标签不存在");
            }
        }
        
        // 创建帖子
        CommunityPost post = new CommunityPost();
        BeanUtils.copyProperties(postDTO, post);
        post.setUserId(userId);
        post.setViewCount(0);
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());
        
        // 处理图片列表
        if (CollectionUtils.isNotEmpty(postDTO.getImages())) {
            post.setImages(gson.toJson(postDTO.getImages()));
        }
        
        if (!this.save(post)) {
            throw new BusinessException("创建帖子失败");
        }
        
        // 创建帖子标签关联
        if (CollectionUtils.isNotEmpty(postDTO.getTagIds())) {
            try {
                List<CommunityPostTag> postTags = postDTO.getTagIds().stream()
                    .distinct() // 确保标签ID不重复
                    .map(tagId -> {
                        CommunityPostTag postTag = new CommunityPostTag();
                        postTag.setPostId(post.getId());
                        postTag.setTagId(tagId);
                        postTag.setCreateTime(LocalDateTime.now());
                        return postTag;
                    })
                    .collect(Collectors.toList());
                
                if (!postTagService.saveBatch(postTags)) {
                    throw new BusinessException("创建帖子标签关联失败");
                }
            } catch (Exception e) {
                log.error("创建帖子标签关联失败: postId={}, tagIds={}, error={}", 
                        post.getId(), postDTO.getTagIds(), e.getMessage());
                throw new BusinessException("创建帖子标签关联失败");
            }
        }
        
        return post.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePost(Long userId, Long id, CommunityPostDTO postDTO) {
        // 验证帖子是否存在且属于当前用户
        CommunityPost existingPost = this.getById(id);
        if (existingPost == null) {
            throw new BusinessException("帖子不存在");
        }
        if (!existingPost.getUserId().equals(userId)) {
            throw new BusinessException("无权修改此帖子");
        }

        // 更新帖子基本信息
        CommunityPost post = new CommunityPost();
        BeanUtils.copyProperties(postDTO, post);
        post.setId(id);
        post.setUpdateTime(LocalDateTime.now());
        if (!this.updateById(post)) {
            throw new BusinessException("更新帖子失败");
        }

        // 更新帖子标签关联
        if (postDTO.getTagIds() != null) {
            try {
                // 删除原有的标签关联
                postTagService.deleteByPostId(id);

                // 创建新的标签关联
                if (CollectionUtils.isNotEmpty(postDTO.getTagIds())) {
                    List<CommunityPostTag> postTags = postDTO.getTagIds().stream()
                        .distinct() // 确保标签ID不重复
                        .map(tagId -> {
                            CommunityPostTag postTag = new CommunityPostTag();
                            postTag.setPostId(id);
                            postTag.setTagId(tagId);
                            postTag.setCreateTime(LocalDateTime.now());
                            return postTag;
                        })
                        .collect(Collectors.toList());

                    if (!postTagService.saveBatch(postTags)) {
                        throw new BusinessException("更新帖子标签关联失败");
                    }
                }
                log.info("更新帖子标签关联成功: postId={}, tagIds={}", id, postDTO.getTagIds());
            } catch (Exception e) {
                log.error("更新帖子标签关联失败: postId={}, tagIds={}, error={}", 
                        id, postDTO.getTagIds(), e.getMessage());
                throw new BusinessException("更新帖子标签关联失败");
            }
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePost(Long userId, Long id) {
        try {
            // 1. 检查帖子是否存在
            CommunityPost post = getById(id);
            if (post == null || post.getDeleted() == 1) {
                log.warn("帖子不存在或已被删除: postId={}", id);
                return false;
            }

            // 2. 检查权限（管理员或帖子作者）
            if (!SecurityUtils.hasRole("ADMIN") && !post.getUserId().equals(userId)) {
                log.warn("无权删除帖子: userId={}, postId={}, postUserId={}", userId, id, post.getUserId());
                throw new BusinessException("无权删除此帖子");
            }

            // 3. 执行删除（使用MyBatis-Plus的逻辑删除）
            boolean result = removeById(id);
            
            if (result) {
                log.info("帖子删除成功: userId={}, postId={}", userId, id);
            } else {
                log.error("帖子删除失败: userId={}, postId={}", userId, id);
            }
            
            return result;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("删除帖子异常: userId={}, postId={}, error={}", userId, id, e.getMessage(), e);
            throw new BusinessException("删除帖子失败");
        }
    }

    @Override
    public CommunityPostDetailDTO getPostDetail(Long userId, Long id) {
        CommunityPost post = getById(id);
        if (post == null) {
            return null;
        }

        CommunityPostDetailDTO detailDTO = new CommunityPostDetailDTO();
        BeanUtils.copyProperties(post, detailDTO);
        detailDTO.setImages(gson.fromJson(post.getImages(), ArrayList.class));
        
        // TODO: 设置用户信息、点赞状态、收藏状态等
        
        return detailDTO;
    }

    @Override
    public IPage<CommunityPostDetailDTO> getPostList(Long currentUserId, Page<CommunityPostDetailDTO> page, Long userId) {
        try {
            // 1. 构建查询条件
        LambdaQueryWrapper<CommunityPost> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunityPost::getDeleted, 0)  // 未删除的帖子
                  .eq(userId != null, CommunityPost::getUserId, userId)  // 如果指定了用户ID，则只查询该用户的帖子
                  .orderByDesc(CommunityPost::getCreateTime);  // 按创建时间倒序排序
            
            // 2. 执行分页查询
        IPage<CommunityPost> postPage = page(new Page<>(page.getCurrent(), page.getSize()), wrapper);
        
            // 3. 转换为DetailDTO并设置额外信息
            List<CommunityPostDetailDTO> records = postPage.getRecords().stream()
                .map(post -> {
                    CommunityPostDetailDTO detailDTO = new CommunityPostDetailDTO();
                    BeanUtils.copyProperties(post, detailDTO);
                    
                    // 设置图片列表
                    if (post.getImages() != null) {
                        try {
                            detailDTO.setImages(gson.fromJson(post.getImages(), ArrayList.class));
                        } catch (Exception e) {
                            log.warn("解析图片列表失败: postId={}, images={}", post.getId(), post.getImages());
                            detailDTO.setImages(new ArrayList<>());
                        }
                    }
                    
                    // 设置用户信息
                    try {
                        UserInfoVO userInfo = userCenterService.getUserInfo(post.getUserId());
                        if (userInfo != null) {
                            detailDTO.setUserNickname(userInfo.getNickname());
                            detailDTO.setUserAvatar(userInfo.getAvatar());
                        }
                    } catch (Exception e) {
                        log.warn("获取用户信息失败: userId={}, error={}", post.getUserId(), e.getMessage());
                        // 设置默认值
                        detailDTO.setUserNickname("用户" + post.getUserId());
                        detailDTO.setUserAvatar("/static/images/default-avatar.jpg");
                    }
                    
                    // 设置当前用户是否点赞
                    if (currentUserId != null) {
                        try {
                            // 查询点赞状态
                            LambdaQueryWrapper<CommunityLike> likeWrapper = new LambdaQueryWrapper<>();
                            likeWrapper.eq(CommunityLike::getUserId, currentUserId)
                                     .eq(CommunityLike::getTargetId, post.getId())
                                     .eq(CommunityLike::getTargetType, 1);
                            detailDTO.setIsLiked(likeMapper.selectCount(likeWrapper) > 0);
                            
                            // 查询收藏状态
                            LambdaQueryWrapper<CommunityFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
                            favoriteWrapper.eq(CommunityFavorite::getUserId, currentUserId)
                                         .eq(CommunityFavorite::getPostId, post.getId());
                            detailDTO.setIsFavorited(favoriteMapper.selectCount(favoriteWrapper) > 0);
                        } catch (Exception e) {
                            log.warn("获取用户交互状态失败: userId={}, postId={}, error={}", 
                                   currentUserId, post.getId(), e.getMessage());
                            detailDTO.setIsLiked(false);
                            detailDTO.setIsFavorited(false);
                        }
                    } else {
                        detailDTO.setIsLiked(false);
                        detailDTO.setIsFavorited(false);
                    }
                    
                    return detailDTO;
                })
                .collect(Collectors.toList());
            
            // 4. 构建返回结果
            IPage<CommunityPostDetailDTO> result = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
            result.setRecords(records);
            
            return result;
        } catch (Exception e) {
            log.error("获取帖子列表失败: currentUserId={}, userId={}, error={}", currentUserId, userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean likePost(Long userId, Long id) {
        try {
            // 检查帖子是否存在
            CommunityPost post = getById(id);
            if (post == null) {
                log.warn("帖子不存在: postId={}", id);
                return false;
            }

            // 尝试删除已存在的点赞记录
            LambdaQueryWrapper<CommunityLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(CommunityLike::getUserId, userId)
                      .eq(CommunityLike::getTargetId, id)
                      .eq(CommunityLike::getTargetType, 1);
            
            if (likeMapper.delete(likeWrapper) > 0) {
                // 如果删除成功，说明之前已点赞，现在是取消点赞
                post.setLikeCount(Math.max(0, post.getLikeCount() - 1));
                updateById(post);
                log.info("取消点赞成功: userId={}, postId={}", userId, id);
                return false;
            }

            // 如果没有删除任何记录，说明之前未点赞，现在添加点赞
            CommunityLike like = new CommunityLike();
            like.setUserId(userId);
            like.setTargetId(id);
            like.setTargetType(1); // 1-帖子
            like.setCreateTime(LocalDateTime.now());
            
            try {
                likeMapper.insert(like);
                // 更新帖子点赞数
                post.setLikeCount(post.getLikeCount() + 1);
                updateById(post);
                // 发送点赞通知
                sendLikeNotification(userId, post);
                log.info("点赞成功: userId={}, postId={}", userId, id);
                return true;
            } catch (Exception e) {
                // 如果插入失败（比如并发情况下已经存在），则视为已点赞
                log.warn("点赞记录已存在: userId={}, postId={}", userId, id);
                return false;
            }
        } catch (Exception e) {
            log.error("点赞操作失败: userId={}, postId={}, error={}", userId, id, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unlikePost(Long userId, Long id) {
        try {
            // 检查帖子是否存在
            CommunityPost post = getById(id);
            if (post == null) {
                log.warn("帖子不存在: postId={}", id);
                return false;
            }

            // 检查是否已点赞
            LambdaQueryWrapper<CommunityLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(CommunityLike::getUserId, userId)
                      .eq(CommunityLike::getTargetId, id)
                      .eq(CommunityLike::getTargetType, 1);
            if (likeMapper.delete(likeWrapper) == 0) {
                log.warn("未点赞过: userId={}, postId={}", userId, id);
                return false;
            }

            // 更新帖子点赞数
            post.setLikeCount(Math.max(0, post.getLikeCount() - 1));
            updateById(post);

            log.info("取消点赞成功: userId={}, postId={}", userId, id);
            return true;
        } catch (Exception e) {
            log.error("取消点赞失败: userId={}, postId={}, error={}", userId, id, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean favoritePost(Long userId, Long id) {
        try {
            // 检查帖子是否存在
            CommunityPost post = getById(id);
            if (post == null) {
                log.warn("帖子不存在: postId={}", id);
                return false;
            }

            // 检查是否已收藏
            LambdaQueryWrapper<CommunityFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
            favoriteWrapper.eq(CommunityFavorite::getUserId, userId)
                          .eq(CommunityFavorite::getPostId, id);
            if (favoriteMapper.selectCount(favoriteWrapper) > 0) {
                log.warn("已经收藏过: userId={}, postId={}", userId, id);
                return false;
            }

            // 添加收藏记录
            CommunityFavorite favorite = new CommunityFavorite();
            favorite.setUserId(userId);
            favorite.setPostId(id);
            favorite.setCreateTime(LocalDateTime.now());
            favoriteMapper.insert(favorite);

            // 发送收藏通知
            sendFavoriteNotification(userId, post);

            log.info("收藏成功: userId={}, postId={}", userId, id);
            return true;
        } catch (Exception e) {
            log.error("收藏失败: userId={}, postId={}, error={}", userId, id, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unfavoritePost(Long userId, Long id) {
        try {
            // 检查帖子是否存在
            CommunityPost post = getById(id);
            if (post == null) {
                log.warn("帖子不存在: postId={}", id);
                return false;
            }

            // 删除收藏记录
            LambdaQueryWrapper<CommunityFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
            favoriteWrapper.eq(CommunityFavorite::getUserId, userId)
                          .eq(CommunityFavorite::getPostId, id);
            if (favoriteMapper.delete(favoriteWrapper) == 0) {
                log.warn("未收藏过: userId={}, postId={}", userId, id);
                return false;
            }

            log.info("取消收藏成功: userId={}, postId={}", userId, id);
            return true;
        } catch (Exception e) {
            log.error("取消收藏失败: userId={}, postId={}, error={}", userId, id, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public IPage<CommunityPostDetailDTO> getFavoritePosts(Long userId, Page<CommunityPostDetailDTO> page) {
        try {
            // 查询用户收藏的帖子ID列表
            LambdaQueryWrapper<CommunityFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
            favoriteWrapper.eq(CommunityFavorite::getUserId, userId)
                         .orderByDesc(CommunityFavorite::getCreateTime);
            
            Page<CommunityFavorite> favoritePage = new Page<>(page.getCurrent(), page.getSize());
            IPage<CommunityFavorite> favoriteResult = favoriteMapper.selectPage(favoritePage, favoriteWrapper);

            // 查询帖子详情
            List<CommunityPostDetailDTO> records = favoriteResult.getRecords().stream()
                .map(favorite -> getPostDetail(userId, favorite.getPostId()))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

            // 构建返回结果
            IPage<CommunityPostDetailDTO> result = new Page<>(page.getCurrent(), page.getSize(), favoriteResult.getTotal());
            result.setRecords(records);
            return result;
        } catch (Exception e) {
            log.error("获取收藏列表失败: userId={}, error={}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public IPage<CommunityPostDetailDTO> getPostsByTag(Long currentUserId, Page<CommunityPostDetailDTO> page, Long tagId) {
        try {
            // 获取标签对应的帖子ID列表
            List<Long> postIds = postTagService.getPostIdsByTagId(tagId);
            if (postIds.isEmpty()) {
                // 如果没有找到帖子，返回空页
                IPage<CommunityPostDetailDTO> emptyPage = new Page<>(page.getCurrent(), page.getSize(), 0);
                emptyPage.setRecords(new ArrayList<>());
                return emptyPage;
            }

            // 构建查询条件
            LambdaQueryWrapper<CommunityPost> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(CommunityPost::getId, postIds)
                  .eq(CommunityPost::getDeleted, 0)
                  .orderByDesc(CommunityPost::getCreateTime);

            // 执行分页查询
            IPage<CommunityPost> postPage = page(new Page<>(page.getCurrent(), page.getSize()), wrapper);

            // 转换为DetailDTO并设置额外信息
            List<CommunityPostDetailDTO> records = postPage.getRecords().stream()
                .map(post -> {
                    CommunityPostDetailDTO detailDTO = new CommunityPostDetailDTO();
                    BeanUtils.copyProperties(post, detailDTO);

                    // 设置图片列表
                    if (post.getImages() != null) {
                        try {
                            detailDTO.setImages(gson.fromJson(post.getImages(), ArrayList.class));
                        } catch (Exception e) {
                            log.warn("解析图片列表失败: postId={}, images={}", post.getId(), post.getImages());
                            detailDTO.setImages(new ArrayList<>());
                        }
                    }

                    // 设置用户信息
                    try {
                        UserInfoVO userInfo = userCenterService.getUserInfo(post.getUserId());
                        if (userInfo != null) {
                            detailDTO.setUserNickname(userInfo.getNickname());
                            detailDTO.setUserAvatar(userInfo.getAvatar());
                        }
                    } catch (Exception e) {
                        log.warn("获取用户信息失败: userId={}, error={}", post.getUserId(), e.getMessage());
                        detailDTO.setUserNickname("用户" + post.getUserId());
                        detailDTO.setUserAvatar("/static/images/default-avatar.jpg");
                    }

                    // 设置当前用户是否点赞和收藏
                    if (currentUserId != null) {
                        try {
                            // 查询点赞状态
                            LambdaQueryWrapper<CommunityLike> likeWrapper = new LambdaQueryWrapper<>();
                            likeWrapper.eq(CommunityLike::getUserId, currentUserId)
                                     .eq(CommunityLike::getTargetId, post.getId())
                                     .eq(CommunityLike::getTargetType, 1);
                            detailDTO.setIsLiked(likeMapper.selectCount(likeWrapper) > 0);

                            // 查询收藏状态
                            LambdaQueryWrapper<CommunityFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
                            favoriteWrapper.eq(CommunityFavorite::getUserId, currentUserId)
                                         .eq(CommunityFavorite::getPostId, post.getId());
                            detailDTO.setIsFavorited(favoriteMapper.selectCount(favoriteWrapper) > 0);
                        } catch (Exception e) {
                            log.warn("获取用户交互状态失败: userId={}, postId={}, error={}", 
                                   currentUserId, post.getId(), e.getMessage());
                            detailDTO.setIsLiked(false);
                            detailDTO.setIsFavorited(false);
                        }
                    } else {
                        detailDTO.setIsLiked(false);
                        detailDTO.setIsFavorited(false);
                    }

                    return detailDTO;
                })
                .collect(Collectors.toList());

            // 构建返回结果
            IPage<CommunityPostDetailDTO> result = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
            result.setRecords(records);
            return result;
        } catch (Exception e) {
            log.error("获取标签帖子列表失败: tagId={}, currentUserId={}, error={}", 
                    tagId, currentUserId, e.getMessage(), e);
            throw e;
        }
    }

    private void sendLikeNotification(Long userId, CommunityPost post) {
        try {
            // 获取用户信息
            UserInfoVO userInfo = userCenterService.getUserInfo(userId);
            if (userInfo == null) {
                log.warn("用户不存在: userId={}", userId);
                return;
            }

            // 构建通知消息
            CommunityNotificationDTO notification = new CommunityNotificationDTO();
            notification.setType(1); // 1-点赞帖子
            notification.setOperatorId(userId);
            notification.setOperatorNickname(userInfo.getNickname());
            notification.setOperatorAvatar(userInfo.getAvatar());
            notification.setPostId(post.getId());
            notification.setPostTitle(post.getTitle());
            notification.setCreateTime(LocalDateTime.now());

            // 构建消息详情
            MessageDetailDTO message = new MessageDetailDTO();
            message.setType(1); // 1-系统通知
            message.setTitle("收到新的点赞");
            message.setContent(gson.toJson(notification));
            message.setUserId(post.getUserId()); // 发送给帖子作者

            // 发送WebSocket消息
            messageWebSocket.sendMessage(post.getUserId(), message);
        } catch (Exception e) {
            log.error("发送点赞通知失败: userId={}, postId={}", userId, post.getId(), e);
        }
    }

    private void sendFavoriteNotification(Long userId, CommunityPost post) {
        try {
            // 获取用户信息
            UserInfoVO userInfo = userCenterService.getUserInfo(userId);
            if (userInfo == null) {
                log.warn("用户不存在: userId={}", userId);
                return;
            }

            // 构建通知消息
            CommunityNotificationDTO notification = new CommunityNotificationDTO();
            notification.setType(2); // 2-收藏帖子
            notification.setOperatorId(userId);
            notification.setOperatorNickname(userInfo.getNickname());
            notification.setOperatorAvatar(userInfo.getAvatar());
            notification.setPostId(post.getId());
            notification.setPostTitle(post.getTitle());
            notification.setCreateTime(LocalDateTime.now());

            // 构建消息详情
            MessageDetailDTO message = new MessageDetailDTO();
            message.setType(1); // 1-系统通知
            message.setTitle("收到新的收藏");
            message.setContent(gson.toJson(notification));
            message.setUserId(post.getUserId()); // 发送给帖子作者

            // 发送WebSocket消息
            messageWebSocket.sendMessage(post.getUserId(), message);
        } catch (Exception e) {
            log.error("发送收藏通知失败: userId={}, postId={}", userId, post.getId(), e);
        }
    }

    @Override
    public String uploadImage(Long userId, MultipartFile file) {
        try {
            return fileUploadUtils.uploadFile(file, "community/" + userId);
        } catch (Exception e) {
            log.error("上传图片失败: userId={}, fileName={}", userId, file.getOriginalFilename(), e);
            throw new BusinessException("上传图片失败：" + e.getMessage());
        }
    }
} 